<template>
  <div class="error-handling-example">
    <el-card header="异常处理使用示例">
      <div class="example-section">
        <h3>1. API调用错误处理</h3>
        <el-space>
          <el-button @click="testBusinessError" type="warning">
            测试业务异常
          </el-button>
          <el-button @click="testSystemError" type="danger">
            测试系统异常
          </el-button>
          <el-button @click="testAuthError" type="info">
            测试认证异常
          </el-button>
          <el-button @click="testNetworkError" type="primary">
            测试网络异常
          </el-button>
        </el-space>
      </div>

      <div class="example-section">
        <h3>2. 表单验证错误处理</h3>
        <el-form :model="userForm" :rules="userRules" ref="userFormRef">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userForm.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item>
            <el-button @click="testValidationError" type="primary">
              测试验证错误
            </el-button>
            <el-button @click="submitForm" type="success">
              提交表单
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="example-section">
        <h3>3. 文件上传错误处理</h3>
        <el-upload
          :before-upload="handleFileUpload"
          :show-file-list="false"
          action="#"
        >
          <el-button type="primary">选择文件上传</el-button>
        </el-upload>
      </div>

      <div class="example-section">
        <h3>4. 自定义错误处理</h3>
        <el-space>
          <el-button @click="testCustomError" type="warning">
            自定义业务错误
          </el-button>
          <el-button @click="testValidationErrors" type="info">
            批量验证错误
          </el-button>
        </el-space>
      </div>
    </el-card>

    <!-- 错误信息显示区域 -->
    <el-card header="错误信息显示" style="margin-top: 20px;" v-if="lastError">
      <div class="error-info">
        <p><strong>错误码:</strong> {{ lastError.errorCode }}</p>
        <p><strong>错误消息:</strong> {{ lastError.errorMessage }}</p>
        <p><strong>错误分类:</strong> {{ lastError.errorCategory }}</p>
        <p><strong>错误级别:</strong> {{ lastError.errorLevel }}</p>
        <p><strong>用户提示:</strong> {{ lastError.userMessage }}</p>
        <p v-if="lastError.suggestion"><strong>建议方案:</strong> {{ lastError.suggestion }}</p>
        <p v-if="lastError.requestId"><strong>请求ID:</strong> {{ lastError.requestId }}</p>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  handleApiError, 
  handleValidationError, 
  handleBusinessError,
  handleSystemError,
  createError,
  ErrorType 
} from '../utils/errorHandler'
import request from '../utils/request'

// 表单数据
const userForm = reactive({
  username: '',
  email: ''
})

// 表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const userFormRef = ref()
const lastError = ref(null)

// 1. 测试业务异常
const testBusinessError = async () => {
  try {
    // 模拟API调用返回业务异常
    await request.post('/api/test/business-error')
  } catch (error) {
    const errorInfo = handleApiError(error, {
      showNotification: true,
      duration: 5000
    })
    lastError.value = errorInfo
  }
}

// 2. 测试系统异常
const testSystemError = async () => {
  try {
    // 模拟API调用返回系统异常
    await request.post('/api/test/system-error')
  } catch (error) {
    const errorInfo = handleApiError(error, {
      showMessage: true,
      showDetails: true
    })
    lastError.value = errorInfo
  }
}

// 3. 测试认证异常
const testAuthError = async () => {
  try {
    // 模拟API调用返回认证异常
    await request.post('/api/test/auth-error')
  } catch (error) {
    const errorInfo = handleApiError(error)
    lastError.value = errorInfo
  }
}

// 4. 测试网络异常
const testNetworkError = async () => {
  try {
    // 模拟网络错误
    await request.post('http://invalid-url.com/api/test')
  } catch (error) {
    const errorInfo = handleApiError(error, {
      showNotification: true
    })
    lastError.value = errorInfo
  }
}

// 5. 测试验证错误
const testValidationError = () => {
  // 模拟验证错误
  const validationErrors = {
    username: '用户名不能为空',
    email: '邮箱格式不正确',
    phone: '手机号码格式不正确'
  }
  
  handleValidationError(validationErrors)
  
  lastError.value = createError('50003', '数据验证失败', ErrorType.VALIDATION)
}

// 6. 提交表单
const submitForm = async () => {
  try {
    // 先进行前端验证
    await userFormRef.value.validate()
    
    // 模拟提交表单
    const response = await request.post('/api/users', userForm)
    ElMessage.success('用户创建成功')
    
    // 清空表单
    userFormRef.value.resetFields()
    lastError.value = null
  } catch (error) {
    if (error.errors) {
      // 表单验证错误
      handleValidationError(error.errors)
    } else {
      // API错误
      const errorInfo = handleApiError(error)
      lastError.value = errorInfo
    }
  }
}

// 7. 文件上传错误处理
const handleFileUpload = (file) => {
  // 检查文件大小
  if (file.size > 10 * 1024 * 1024) {
    handleBusinessError('60005', '文件大小超出限制', {
      duration: 4000
    })
    return false
  }
  
  // 检查文件类型
  const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
  if (!allowedTypes.includes(file.type)) {
    handleBusinessError('60006', '不支持的文件类型', {
      duration: 4000
    })
    return false
  }
  
  // 模拟上传成功
  ElMessage.success('文件上传成功')
  return false // 阻止自动上传
}

// 8. 自定义错误处理
const testCustomError = () => {
  const errorInfo = handleBusinessError('20002', '用户名已存在', {
    duration: 4000
  })
  lastError.value = errorInfo
}

// 9. 批量验证错误
const testValidationErrors = () => {
  const errors = [
    { field: 'username', message: '用户名不能为空' },
    { field: 'email', message: '邮箱格式不正确' },
    { field: 'password', message: '密码长度不能少于6位' }
  ]
  
  handleValidationError(errors)
  
  lastError.value = createError('50003', '表单验证失败', ErrorType.VALIDATION)
}
</script>

<style scoped>
.error-handling-example {
  padding: 20px;
}

.example-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.example-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #303133;
}

.error-info {
  background-color: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 4px;
  padding: 15px;
}

.error-info p {
  margin: 5px 0;
  line-height: 1.5;
}

.error-info strong {
  color: #f56c6c;
}
</style>
